<?php


namespace App\Models;


use App\Services\ZlbService;
use Illuminate\Database\Eloquent\Model;

class ZlbOrderLease extends Model
{
    protected $table = "order_lease";
    protected $primaryKey = 'id';
    public $timestamps = false;

    /**
     * 订单账单承诺新增信息
     * @param $order
     * @param $lease
     */
    public static function leasePromiseAdd($order,$lease){
        foreach ($lease as $value){
            $leaseData = [
                'order_no'=>$order['trade_no'],
                'which_period'=>$value['which_period'],
                'rent'=>$value['rent'],
                'begin_time'=>dateFormat($value['begin_time']),
                'end_time'=>dateFormat($value['end_time']),
                'create_time'=>dateFormat($value['create_time']),
                'status'=>$value['status'],
                'alipay_trade_no'=>$value['trade_no'],
                'period'=>ZlbService::LEASE_LIMIT_DAY,
            ];
            ZlbOrderLease::insertGetId($leaseData);
        }
    }

    /**
     * 履约信息新增数据
     * @param $orderNo
     * @param $lease
     * @param $type
     */
    public static function leaseAdd($orderNo,$lease,$type){
        if($lease['pay_type'] == OrderLease::LEASE_PAY_TYPE_ANTCHAIN){
            $pay_type = 2;
        }elseif ($lease['pay_type'] == OrderLease::LEASE_PAY_TYPE_ZM){
            $pay_type = 1;
        }else{
            $pay_type = 3;
        }
        $data = [
            'status'=>$lease['status'],
            'pay_time'=>dateFormat($lease['pay_time']),
            'rent_status'=>$type,
            'pay_type'=>$pay_type,
            'charge'=>toServiceCharge($lease['rent']),
            'alipay_trade_no'=>$lease['trade_no'],

        ];
        ZlbOrderLease::where(['order_no'=>$orderNo,'which_period'=>$lease['which_period']])->update($data);
    }

    /**
     * 履约信息上链
     * @param $orderNo
     * @param $lease
     * @param $request
     * @param $notary
     */
    public static function leaseUpdate($orderNo,$lease,$request,$notary){
        $res = ZlbService::format($notary);
        if($res['status'] == ZlbService::STATUS_YES){
            //成功
            ZlbService::requestLog('上传订单履约成功',$request,$res);
        }else{
            //失败
            ZlbService::requestLog('上传订单履约失败',$request,$res);
        }
        $update = [
            'tx_hash'=>$res['tx_hash'],
            'chain_status'=>$res['status'],
            'chain_params'=>ZlbService::paramsResponse($request,$notary),
            'chain_time'=>dateFormat(time()),
        ];
        ZlbOrderLease::where(['order_no'=>$orderNo,'which_period'=>$lease['which_period']])->update($update);
    }
}
